import React from 'react'
import { Toast, Modal } from 'antd-mobile'
import Spin from 'zhang-components/Spin'
import debounce from 'lodash/debounce'
import { gw, gw_wx, boya } from './http.spec'
// import mockData from './mockData'
// import Mock from 'mockjs'
import {
  REQUEST_TIMEOUT_CODE,
  REQUEST_FORCEOUT_CODE,
  REQUEST_ERROR_CODE_NO_PROCESSING,
  REQUEST_AUTH_ERROR_CODE,
  REQUEST_STATUS_ERROR_CODE,
  REQUEST_EMPTY_DATA_CODE_GW
} from 'zhang-constants/constant'

const errorDict = {
  404: '未找到相应资源 - 404 - zhang',
  500: '服务器内部错误 - 500 - zhang',
  503: '服务目前不可用 - 503 - zhang',
  3: '请求被重定向 - zhang',
  4: '请求出现错误 - zhang',
  5: '服务器出现错误 - zhang'
}
// 抛错误码
const getErrDesc = statusCode => {
  let result = errorDict[statusCode]
  if (!result) {
    const errStart = statusCode.toString().charAt(0)
    result = errorDict[errStart]
  }
  return result || '出现未知错误！请联系管理员-zhang'
}
// 返回数据null、'null'处理为''
function responseNullHandle(data) {
  if (data === null) {
    return ''
  }
  if (Array.isArray(data)) {
    data = data.map(function (item) {
      return responseNullHandle(item)
    })
  } else if (typeof data === 'object') {
    for (let key in data) {
      if (Object.prototype.hasOwnProperty.call(data, key)) {
        data[key] = responseNullHandle(data[key])
      }
    }
  } else if (typeof data === 'string') {
    if (data === 'null') {
      data = ''
    }
  }
  return data
}
// 数据拦截
let timeout = false
const debounceErrorHandle = debounce(function (e) {
  if (e.code === REQUEST_TIMEOUT_CODE || e.code === REQUEST_FORCEOUT_CODE) {
    if (!timeout) {
      timeout = true
      Modal.alert('提示', '会话超时，请重新登录-张', [
        {
          text: '确认',
          onPress: () => { }
        }
      ])
    }
  } else if (e.code === REQUEST_STATUS_ERROR_CODE) {
    Toast.fail(e.msg)
  } else if ([...REQUEST_ERROR_CODE_NO_PROCESSING].indexOf(e.code) > -1) {
    // 不处理
  } else if (window.location.pathname.indexOf('zhang') > -1) {
    // 不处理
  } else if (REQUEST_EMPTY_DATA_CODE_GW === e.code) {
    Modal.alert('提示', e.msg, [
      { text: '返回', onPress: () => window.history.back() }
    ])
  } else if (REQUEST_AUTH_ERROR_CODE === e.code) {
    e.msg = '这是一条修改后的message'
    Toast.fail(e.msg, 2)
  } else {
    if (e.msg) {
      Toast.fail(e.msg, 2)
    } else if (e.response) {
      Toast.fail(getErrDesc(e.response.status), 2)
    } else if (e.message === 'Network Error') {
      Toast.fail('这是一条 Network Error')
    }
  }
}, 500)
// 错误处理
const errorHandler = function (e) {
  debounceErrorHandle(e)
  if ([REQUEST_TIMEOUT_CODE, REQUEST_FORCEOUT_CODE].indexOf(e.code) > -1) {
    return new Promise(function (resolve) {
      setTimeout(function () {
        resolve()
      }, 100000000)
    })
  }
  throw e
}
// 错误处理-直接抛
const errorHandlerWithoutHandle = function (e) {
  throw e
}
// loading处理
let loadingCount = 0
const loadingHandler = (function () {
  return {
    request(loading) {
      return function (res) {
        if (loading) {
          if (loadingCount === 0) {
            Toast.info(<Spin type="oval" style={{ height: '24px', width: '24px' }} />, 0)
          }
          loadingCount++
        }
        // Mock.mock(/\QryProjectInformation111/, mockData.QryProjectInformation111)
        // Mock.mock(/\QryProjectInformation222/, mockData.QryProjectInformation222)
        return res
      }
    },
    response(loading) {
      return function (res) {
        if (loading) {
          loadingCount--
          if (loadingCount <= 0) {
            Toast.hide()
            loadingCount = 0
          }
        }
        return res
      }
    }
  }
})()

function httpFactory({ request, response }) {
  return {
    post(api, data = {}, isLoading = false, isEncrypt = true, supressError = false) {
      return Promise.resolve(data)
        .then(loadingHandler.request(isLoading))
        .then(request(isEncrypt)(api))
        .then(loadingHandler.response(isLoading))
        .then(response(isEncrypt))
        .then(responseNullHandle)
        .catch(!supressError ? errorHandler : errorHandlerWithoutHandle)
    }
  }
}

const GW = httpFactory(gw)
const GW_WX = httpFactory(gw_wx)
const BOYA = httpFactory(boya)

export default GW
export { GW_WX, BOYA }
